package io.renren.modules.app.utils;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RestTemplateFactory {

    /**
     * 每个ip地址上最大的链接数
     */
    private static int defaultMaxPerRoute = 100;
    /**
     * 连接池中最大的链接条数
     */
    private static int maxTotle = 200;
    /**
     * 创建连接最大时间
     */
    private static int connectTimeout = 10 * 1000;

    private static HttpClient _client;

    static {
        /**
         * 读取数据库或者配置文件 修改参数
         */
        PoolingClientConnectionManager pccm = new PoolingClientConnectionManager();
        pccm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        pccm.setMaxTotal(maxTotle);
        pccm.closeIdleConnections(1000, TimeUnit.SECONDS); // 链接空闲时间
        _client = new DefaultHttpClient(pccm);
        _client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        _client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 50000); // 发送数据超时时间
    }

    /**
     * 返回restTemplate
     *
     * @return
     */
    public static String getResponse(HttpUriRequest post) {
        try {
            HttpResponse response = _client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            entity = new GzipDecompressingEntity(response.getEntity());
                            break;
                        }
                    }
                }
                String charset = EntityUtils.getContentCharSet(entity) == null ? "utf-8"
                        : EntityUtils.getContentCharSet(entity);
                String body = EntityUtils.toString(entity, charset);
                return body;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static HttpGet generateGet(String url, Map<String, String> headers) {
        // 替换空格为%20
        url = url.replaceAll(" ", "%20");
        HttpGet get = new HttpGet(url);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            get.addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
        }
        return get;
    }

    public static HttpPost postForm(String url, Map<String, String> params, Map<String, String> headers) {
        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpost.addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
        }
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return httpost;
    }

}
